//
//  MemberUpdateLoginPwdViewController.m
//  myhuibao
//
//  Created by lijun on 13-3-11.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "MemberFavoriteLisViewController.h"
#import "RestaurantDetailViewController.h"
#import <UIKit/UIKit.h>
#import "Config.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
#import "SearchCell.h"

@interface MemberFavoriteLisViewController ()

@end

@implementation MemberFavoriteLisViewController
@synthesize mainTable;
static int stype=1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void) viewWillAppear:(BOOL)YSE{
    stype=1;
    [super viewWillAppear:YES];
    wqTable=mainTable;
    pageIndex=1;
    NSURL *url = [NSURL URLWithString:url_getfavoriteList];//[NSString stringWithFormat:@"%@?pageIndex=%d",url_searchList,pageIndex++]] ;
    //    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
    
    int memberId = [[Config Instance] getMemberId];
    NSString *password=[[Config Instance] getPassword];
    //NSString *password=@"xiejin";
    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
    [request setPostValue:password forKey:@"password"];
    [request setPostValue:sid forKey:@"memberID"];
    
    [request setDelegate: self];
    [request startAsynchronous];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    wqTable=mainTable;
    pageIndex=1;
    NSURL *url = [NSURL URLWithString:url_getfavoriteList];//[NSString stringWithFormat:@"%@?pageIndex=%d",url_searchList,pageIndex++]] ;
    //    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
    
    int memberId = [[Config Instance] getMemberId];
    NSString *password=[[Config Instance] getPassword];
    //NSString *password=@"xiejin";
    NSString *sid=[NSString stringWithFormat:@"%d",memberId];
    [request setPostValue:password forKey:@"password"];
    [request setPostValue:sid forKey:@"memberID"];
    
    [request setDelegate: self];
    [request startAsynchronous];
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    //[mainTable release];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}



//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)requestFinished:(ASIHTTPRequest *)request
{
    
      NSString *jsonStr = [request responseString];
      //NSLog(@"%@",jsonStr);
      NSDictionary *dic = [jsonStr JSONValue];
    if(stype==1){
      tableDataArray = [dic valueForKey:@"data"];
      //NSLog(@"%@", tableDataArray);
      returnCount = [tableDataArray count];
      delegate=self;
      [mainTable reloadData];
    }
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
      NSError *error = [request error];
      NSLog(@"%@",error);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count+1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"SearchCellIdentifier";
    
    
    if([indexPath row] < ([tableDataArray count])) {
        
        SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        //        if (cell == nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:nil options:nil];
        cell = [array objectAtIndex:0];
        [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        //        }
        
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        
        cell.name = [item valueForKey:@"name"];
        cell.address = [item valueForKey:@"address"] ;
        cell.distance = [item valueForKey:@"distance"] ==[NSNull null]?@"未知" : [NSString stringWithFormat:@"%d",[[item valueForKey:@"distance"] intValue]/1000];
        cell.cuisine = [item valueForKey:@"cuisine"] ==[NSNull null]?@"未知" : [item valueForKey:@"cuisine"];
        cell.discount = [item valueForKey:@"discount"] ==[NSNull null]?@"" : [NSString stringWithFormat:@"%d",[[item valueForKey:@"discount"] intValue]];
        cell.score = [item valueForKey:@"score"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"score"] floatValue]];
        //        NSString *imageName = [[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"ID"];
        // [[[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"image"]stringByAppendingString:@".temp"];
        //        if(imageName == nil || (NSNull *)imageName == [NSNull null])
        //        {
        //            cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
        //            return  cell;
        //        }
        NSString * imageName = [NSString stringWithFormat:@"%d%@",[[[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"ID"] intValue],@".temp"];//[imageName stringByAppendingString:@".temp"];
        //        NSLog(@"%@",imageName);
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
        if (image) {
            cell.imageView.image = image;
        }
        else
        {
            cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
            //placeholder为在未加载完成加载图片时显示的默认图片
        }
        return cell;
        
    }else{
        
        
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        //              if (cell == nil)
        {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                          reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if(returnCount<pageSize){
            cell.textLabel.text=@"";
        }else{
            //创建loadMoreCell
            cell.textLabel.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;
        
    }
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
    cell.imageView.image = [image copy];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        UITableViewCell *loadMoreCell=[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.textLabel.text=str_loading;
        //        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
        //        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?pageIndex=%d",url_searchList,pageIndex++]] ;
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request startSynchronous];
        NSString *jsonStr = [request responseString];
        
        NSDictionary *dic = [jsonStr JSONValue];
        NSMutableArray *array = [dic valueForKey:@"data"];
        returnCount = [array count];
        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        //        [dic release];
        //        [array release];
        return;
    }else{
        RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        view.merchantId =[[item objectForKey:@"ID"] intValue];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
        //        [view release];
        
    }
    //其他cell的事件
    
}
-(void) appendTableWith:(NSMutableArray *)data
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
    {
        stype=2;
         NSDictionary *dic=[tableDataArray objectAtIndex:indexPath.row];
        [tableDataArray removeObjectAtIndex:indexPath.row];
        NSString *favoriteID=[dic valueForKey:@"favoriteID"];
        int memberID=[[Config Instance] getMemberId];
        NSString *password=[[Config Instance]getPassword];
        NSString *sid=[NSString stringWithFormat:@"%d",memberID];
        NSURL *url=[NSURL URLWithString:url_delfavorite];
        ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
        [request setPostValue:sid forKey:@"memberID"];
        [request setPostValue:password forKey:@"password"];
        [request setPostValue:favoriteID
                       forKey:@"favoriteID"];
        [request setDelegate:self];
        [request startAsynchronous];
        [mainTable reloadData];
}


- (IBAction)goBack:(id)sender {
    [super.navigationController
     popViewControllerAnimated:YES];
}

- (void)dealloc {
    [mainTable release];
    [super dealloc];
}

@end
